home *** CD-ROM | disk | FTP | other *** search
/ Chip 2006 June / CHIP 2006-06.2.iso / program / freeware / Democracy-0.8.2.exe / xulrunner / python / BitTorrent / parseargs.py < prev    next >
Encoding:
Python Source  |  2006-04-10  |  4.8 KB  |  147 lines

  1. # The contents of this file are subject to the BitTorrent Open Source License
  2. # Version 1.0 (the License).  You may not copy or use this file, in either
  3. # source code or executable form, except in compliance with the License.  You
  4. # may obtain a copy of the License at http://www.bittorrent.com/license/.
  5. #
  6. # Software distributed under the License is distributed on an AS IS basis,
  7. # WITHOUT WARRANTY OF ANY KIND, either express or implied.  See the License
  8. # for the specific language governing rights and limitations under the
  9. # License.
  10.  
  11. # Written by Bill Bumgarner and Bram Cohen
  12.  
  13. import sys
  14. from types import *
  15. from cStringIO import StringIO
  16.  
  17. from BitTorrent.obsoletepythonsupport import *
  18.  
  19. from BitTorrent import BTFailure, is_frozen_exe
  20. if is_frozen_exe:
  21.     from BitTorrent.GUI import HelpWindow
  22.  
  23. def makeHelp(uiname, defaults):
  24.     ret = ''
  25.     ret += ("Usage: %s " % uiname)
  26.     if uiname.startswith('btlaunchmany'):
  27.         ret += "[OPTIONS] [TORRENTDIRECTORY]\n\n"
  28.         ret += "If a non-option argument is present it's taken as the value\n"\
  29.               "of the torrent_dir option.\n"
  30.     elif uiname == 'btdownloadgui':
  31.         ret += "[OPTIONS] [TORRENTFILES]\n"
  32.     elif uiname.startswith('btdownload'):
  33.         ret += "[OPTIONS] [TORRENTFILE]\n"
  34.     elif uiname == 'btmaketorrent':
  35.         ret += "[OPTION] TRACKER_URL FILE [FILE]\n"
  36.     ret += '\n'
  37.     ret += 'arguments are -\n' + formatDefinitions(defaults, 80)
  38.     return ret
  39.  
  40. def printHelp(uiname, defaults):
  41.     if is_frozen_exe:
  42.         HelpWindow(None, makeHelp(uiname, defaults))
  43.     else:
  44.         print makeHelp(uiname, defaults)
  45.  
  46. def formatDefinitions(options, COLS):
  47.     s = StringIO()
  48.     indent = " " * 10
  49.     width = COLS - 11
  50.  
  51.     if width < 15:
  52.         width = COLS - 2
  53.         indent = " "
  54.  
  55.     for (longname, default, doc) in options:
  56.         if doc == '':
  57.             continue
  58.         s.write('--' + longname + ' <arg>\n')
  59.         if default is not None:
  60.             doc += ' (defaults to ' + repr(default) + ')'
  61.         i = 0
  62.         for word in doc.split():
  63.             if i == 0:
  64.                 s.write(indent + word)
  65.                 i = len(word)
  66.             elif i + len(word) >= width:
  67.                 s.write('\n' + indent + word)
  68.                 i = len(word)
  69.             else:
  70.                 s.write(' ' + word)
  71.                 i += len(word) + 1
  72.         s.write('\n\n')
  73.     return s.getvalue()
  74.  
  75. def usage(str):
  76.     raise BTFailure(str)
  77.  
  78. def format_key(key):
  79.     if len(key) == 1:
  80.         return '-%s'%key
  81.     else:
  82.         return '--%s'%key
  83.  
  84. def parseargs(argv, options, minargs = None, maxargs = None, presets = None):
  85.     config = {}
  86.     for option in options:
  87.         longname, default, doc = option
  88.         config[longname] = default
  89.     args = []
  90.     pos = 0
  91.     if presets is None:
  92.         presets = {}
  93.     else:
  94.         presets = presets.copy()
  95.     while pos < len(argv):
  96.         if argv[pos][:1] != '-':             # not a cmdline option
  97.             args.append(argv[pos])
  98.             pos += 1
  99.         else:
  100.             key, value = None, None
  101.             if argv[pos][:2] == '--':        # --aaa 1
  102.                 if pos == len(argv) - 1:
  103.                     usage('parameter passed in at end with no value')
  104.                 key, value = argv[pos][2:], argv[pos+1]
  105.                 pos += 2
  106.             elif argv[pos][:1] == '-':
  107.                 key = argv[pos][1:2]
  108.                 if len(argv[pos]) > 2:       # -a1
  109.                     value = argv[pos][2:]
  110.                     pos += 1
  111.                 else:                        # -a 1
  112.                     if pos == len(argv) - 1:
  113.                         usage('parameter passed in at end with no value')
  114.                     value = argv[pos+1]
  115.                     pos += 2
  116.             else:
  117.                 raise BTFailure('command line parsing failed at '+argv[pos])
  118.  
  119.             presets[key] = value
  120.     parse_options(config, presets)
  121.     config.update(presets)
  122.     for key, value in config.items():
  123.         if value is None:
  124.             usage("Option %s is required." % format_key(key))
  125.     if minargs is not None and len(args) < minargs:
  126.         usage("Must supply at least %d args." % minargs)
  127.     if maxargs is not None and len(args) > maxargs:
  128.         usage("Too many args - %d max." % maxargs)
  129.     return (config, args)
  130.  
  131. def parse_options(defaults, newvalues):
  132.     for key, value in newvalues.iteritems():
  133.         if not defaults.has_key(key):
  134.             raise BTFailure('unknown key ' + format_key(key))
  135.         try:
  136.             t = type(defaults[key])
  137.             if t is NoneType or t is StringType:
  138.                 newvalues[key] = value
  139.             elif t in (IntType, LongType):
  140.                 newvalues[key] = int(value)
  141.             elif t is FloatType:
  142.                 newvalues[key] = float(value)
  143.             else:
  144.                 assert False
  145.         except ValueError, e:
  146.             raise BTFailure('wrong format of %s - %s' % (format_key(key), str(e)))
  147.